package tech.dongliang.juduocai.upload.controller;

import com.alibaba.fastjson.JSONObject;
import tech.dongliang.juduocai.upload.controller.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping(value = "/upload")
public class ImageUploadController {
    @Value("${file.upload.root}")
    private String root;

    /**
     * 上传图片方法
     *
     * @param request
     * @return
     * @throws NumberFormatException
     * @throws Exception
     */
    @RequestMapping(value = "/images/{pathfix}")
    @ResponseBody
    public JSONObject img(HttpServletRequest request, @PathVariable("pathfix") String pathfix) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile imgFile = multipartRequest.getFileMap().entrySet().iterator().next().getValue();
        request.setAttribute("root", root);
        request.setAttribute("pathfix", pathfix);
        String[] paths = FileUtils.getSavePathByRequest(request, true);
        JSONObject json = FileUtils.saveImage(imgFile, paths);
        String cut = request.getParameter("cut");
        String resize = request.getParameter("resize");
        String id = request.getParameter("id");
        String wh = request.getParameter("wh");
        String scale = request.getParameter("scale");//是否等比，resize传值才有效
        if (json.getBooleanValue("success")) {
            String newFileName = json.getString("url").substring(json.getString("url").lastIndexOf("/") + 1);
            File srcSource = new File(paths[0], newFileName);
            if ("1".equals(wh)) {
                BufferedImage image = ImageIO.read(srcSource);
                int imageWidth = image.getWidth();
                int imageHeitht = image.getHeight();
                json.put("width", imageWidth);
                json.put("height", imageHeitht);
            }
            // url参数cut=x|y|width|height
            if (StringUtils.isNotEmpty(cut)) {
                String target = cut(srcSource, paths, cut);
                json.put("cutUrl", target);
            }
            // url参数resize=width:height|width:height……
            if (StringUtils.isNotEmpty(resize)) {
                Map<String, String> map = resize(srcSource, paths, resize, scale);
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    String target = entry.getValue();
                    target = target.substring(target.lastIndexOf("/") + 1);
                    json.put(entry.getKey(), entry.getValue());
                }
            }
        }
        json.put("id", id);
        return json;
    }

    private static Map<String, String> resize(File srcSource, String[] paths, String resize, String scale) throws Exception {
        String[] rlist = resize.split("\\|");
        Map<String, String> map = new HashMap<>();
        for (String r : rlist) {
            String[] rs = r.split(":");
            if (StringUtils.isNotEmpty(rs[0]) && StringUtils.isNotEmpty(rs[1])) {
                String middlePath = File.separator + r.replace(":", "_");
                String newresizeName = srcSource.getName().substring(0, srcSource.getName().lastIndexOf("."));
                String path = paths[0] + middlePath;
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String userDefineTempFile = path + File.separator + newresizeName;
                if ("1".equals(scale)) {
                    Thumbnails.of(srcSource).size(Integer.parseInt(rs[0]), Integer.parseInt(rs[1])).outputFormat("jpg").toFile(userDefineTempFile);
                } else {
                    FileUtils.resize(srcSource, userDefineTempFile, Integer.parseInt(rs[0]), Integer.parseInt(rs[1]));
                }
                String userTempUrl = paths[1] + middlePath + "/" + newresizeName + ".jpg";
                map.put(r, userTempUrl);
            }
        }
        return map;
    }

    private static String cut(File srcSource, String[] paths, String cut) throws NumberFormatException, Exception {
        String middlePath = File.separator + "cut";
        String newFileName = FileUtils.getRandomFileName();
        // 截取文件的绝对路径
        String path = paths[0] + middlePath;
        File userDefineTempFile = new File(path + File.separator + newFileName);
        if (!userDefineTempFile.getParentFile().exists()) {
            userDefineTempFile.getParentFile().mkdirs();
        }
        String[] temp = cut.split("\\|");
        String x = temp[0]; // 开始截取的x坐标
        String y = temp[1]; // 开始截取的y坐标
        String width = temp[2]; // 需要裁减图片的宽度
        String height = temp[3]; // 需要裁减图片高度
        if (StringUtils.isNotEmpty(x) && StringUtils.isNotEmpty(y) && StringUtils.isNotEmpty(width)
                && StringUtils.isNotEmpty(height)) { // 判断用户是否需要裁减照片

            Long xx = Math.round(Double.parseDouble(x));
            Long yy = Math.round(Double.parseDouble(y));
            Long ww = Math.round(Double.parseDouble(width));
            Long hh = Math.round(Double.parseDouble(height));

            Thumbnails.of(srcSource).scale(1f).sourceRegion(xx.intValue(), yy.intValue(), ww.intValue(), hh.intValue())
                    .outputFormat("jpg").toFile(userDefineTempFile);
        }
        srcSource = userDefineTempFile;
        return paths[1] + middlePath + "/" + newFileName + ".jpg";
    }


}
